package com.cyan.app.workflow.util;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

import com.cyan.app.workflow.AppContext;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * Created by GivenTang on 2015/8/24.
 */
public class Decompress {
    private static final String TAG = "Decompress";

    private static final int BUFFER_SIZE = 1024 * 1;

    /**
     * 如果目标路径为空，则指向APP存储/data/data/PACKAGENAME/app_local目录
     * @param context
     * @param destination
     * @return
     */
    private static String chkDestination(Context context, String destination) {
        if (destination == null || destination.length() == 0)
            destination = context.getDir("local", Activity.MODE_PRIVATE).getAbsolutePath() + "/";

        Logger.e(TAG, "destination = " + destination);

        return destination;
    }

    /**
     * 从assets目录压缩文件解压
     * @param context
     * @param zipFile
     * @param destination
     */
    public static void unzipFromAssets(Context context, String zipFile, String destination) {
        try {
            destination = chkDestination(context, destination);

            InputStream stream = context.getAssets().open(zipFile);
            unzip(stream, destination);
        } catch (IOException e) {
            Logger.e(TAG, "unzip", e);
        }
    }

    /**
     * 从指定文件名解压
     * @param context
     * @param zipFile
     * @param destination
     */
    public static void unzip(Context context, String zipFile, String destination) {
        try {
            destination = chkDestination(context, destination);

            FileInputStream fin = new FileInputStream(zipFile);
            unzip(fin, destination);
        } catch (FileNotFoundException e) {
            Logger.e(TAG, "unzip", e);
        }
    }

    /**
     * 从文件流解压文件
     * @param stream
     * @param destination
     */
    public static void unzip(InputStream stream, String destination) {
        dirChecker(destination, "");
        byte[] buffer = new byte[BUFFER_SIZE];
        try {
            ZipInputStream zin = new ZipInputStream(stream);
            ZipEntry ze = null;

            while ((ze = zin.getNextEntry()) != null) {
                Logger.e(TAG, "Unzipping " + ze.getName());

                if (ze.isDirectory()) {
                    dirChecker(destination, ze.getName());
                } else {
                    File f = new File(destination + ze.getName());
                    /*if (!f.exists())*/ {
                        FileOutputStream fout = new FileOutputStream(destination + ze.getName());
                        int count;
                        while ((count = zin.read(buffer)) != -1) {
                            fout.write(buffer, 0, count);
                        }
                        zin.closeEntry();
                        fout.close();
                    }
                }

            }
            zin.close();
            setSuccess();
        } catch (Exception e) {
            Logger.e(TAG, "unzip", e);
        }
    }

    /**
     * 检测并建立目录
     * @param destination
     * @param dir
     */
    private static void dirChecker(String destination, String dir) {
        File f = new File(destination + dir);

        if (!f.isDirectory()) {
            boolean success = f.mkdirs();
            if (!success) {
                Logger.w(TAG, "Failed to create folder " + f.getName());
            }
        }
    }

    /**
     * 是否已成功解压过
     * @return
     */
    public static boolean isSuccess() {
        SharedPreferences sp = AppContext.getInstance().getSharedPreferences("soccer_settings", Activity.MODE_PRIVATE);
        return sp.getBoolean("zip_success", false);
    }

    /**
     * 标记解压成功
     */
    private static void setSuccess() {
        SharedPreferences sp = AppContext.getInstance().getSharedPreferences("soccer_settings", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean("zip_success", true);
        editor.commit();
    }
}